import http from "../utils/httpRequest";
import { baseConfig, setRoutes } from '@/utils'

export default {
  state: {
    routerList: [],
    dictList: [],
    isClick: false,
    tbLoading: false,
  },
  getters: {
    getDictList: (state) => (type, exclude) => {
      return handleDictList(state, type, exclude)
    },
    getDict(state) {
      return function (type, dicKey) {
        const item = handleDictList(state, type).find(res => res[baseConfig.dict.value]?.toString() === dicKey?.toString()) || {}
        return item[baseConfig.dict.label]
      }
    },
    getIsClick(state) {
      return state.isClick
    },
  },
  mutations: {
    setRouterList(state, routerList) {
      state.routerList = routerList
    },
    setDictList(state, dictList) {
      state.dictList = dictList
    },
    setIsClick(state, isClick) {
      state.isClick = isClick
    },
    setTableLoading(state, loading) {
      state.tbLoading = loading
    },
  },
  actions: {
    initRouter({ commit }, payload = baseConfig.router.url) {
      // 如果直接传递菜单数据，那么不调用接口获取
      if (Array.isArray(payload)) {
        commit('setRouterList', payload)
        localStorage.setItem('routerList', JSON.stringify(payload))
        if (baseConfig.router.dynamic && baseConfig.router.import) {
          setDynamic(payload)
        }
        return false
      }
      http({
        url: http.adornUrl(payload),
        method: 'get',
        data: http.adornData({
        }, false)
      }).then(({ data }) => {
        if (data && data.code === 200) {
          commit('setRouterList', data.data)
          localStorage.setItem('routerList', JSON.stringify(data.data))
          if (baseConfig.router.dynamic && baseConfig.router.import) {
            setDynamic(data.data)
          }
        }
      })
    },
    initDict({ commit }, url = baseConfig.dict.url) {
      http({
        url: http.adornUrl(url),
        method: 'get',
        data: http.adornData({
        }, false)
      }).then(({ data }) => {
        if (data && data.code === 200) {
          commit('setDictList', data.data)
          localStorage.setItem('dictList', JSON.stringify(data.data))
        }
      })
    },
  },
}



function handleDictList(state, type, exclude = []) {
  return state.dictList.filter(res => res[baseConfig.dict.type] === type && exclude.indexOf(res[baseConfig.dict.value]) === -1)
}

function setDynamic(list) {
  let routeList = []
  list.forEach(res => {
    if (res.children) {
      res.children = res.children.map(inner => {
        inner.path = (res.path === '/' ? '' : res.path) + '/' + inner.path
        inner.meta = { ...inner.meta, parent: res.meta }
        return inner
      })
      routeList.push(...res.children)
    }
  })
  let dyRoutes = routeList.map(res => {
    return {
      path: res.path,
      name: res.name,
      component: baseConfig.router.import(res.component),
      meta: res.meta
    }
  })
  setRoutes(baseConfig.router.starter, dyRoutes, baseConfig.router.baseRouter)
}